package com.kk.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kk.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 公共字段自动填充处理器
 * 符合阿里巴巴《Java 开发手册》规范：严禁出现魔法值，使用常量，明确日志等级。
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_BY = "updateBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("Start insert fill ...");

        LocalDateTime now = LocalDateTime.now();

        strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, now);
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);

        // 一般从上下文（如 SecurityContextHolder）中取当前登录用户
        String currentUser = getCurrentUsername();
        strictInsertFill(metaObject, CREATE_BY, String.class, currentUser);
        strictInsertFill(metaObject, UPDATE_BY, String.class, currentUser);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("Start update fill ...");

        LocalDateTime now = LocalDateTime.now();
        strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);

        String currentUser = getCurrentUsername();
        strictUpdateFill(metaObject, UPDATE_BY, String.class, currentUser);
    }

    /**
     * 获取当前登录用户名
     * 实际项目中可从 Spring Security / Sa-Token 等上下文中获取
     */
    private String getCurrentUsername() {
        // TODO: 从安全上下文中获取登录用户名
        return SecurityUtils.getCurrentUsername(); // 兜底值
    }
}